package com.cyl.manager.lbs.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.service.MyBaseService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.livesass.ProductVideoService;
import com.ruoyi.system.service.ISysConfigService;
import com.volcengine.model.beans.livesaas.ProductMsgAPI;
import com.volcengine.model.livesaas.response.GetActivityProductAPIResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cyl.manager.lbs.mapper.LbsProductMapper;
import com.cyl.manager.lbs.mapper.LbsZbjlMapper;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.cyl.manager.act.service.CouponActivityService;
import com.cyl.manager.lbs.domain.LbsProduct;
import com.cyl.manager.lbs.pojo.query.LbsAddProductQuery;
import com.cyl.manager.lbs.pojo.query.LbsProductQuery;
import com.cyl.manager.oms.domain.entity.OrderItemPrepare;
import com.cyl.manager.oms.mapper.OrderItemPrepareMapper;
import com.cyl.manager.pms.domain.entity.Product;
import com.cyl.manager.pms.mapper.ProductMapper;

/**
 * 直播商品Service业务层处理
 *
 *
 * @author hxw
 */
@Service
public class LbsProductService extends MyBaseService<LbsProductMapper, LbsProduct>{

    @Autowired
    private LbsProductMapper lbsProductMapper;

    
    @Autowired
    private ISysConfigService sysConfigService;
    
    @Autowired
    private ProductVideoService productVideoService;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private LbsZbjlMapper lbsZbjlMapper;
    
    /**
     * 查询直播商品
     *
     * @param id 直播商品主键
     * @return 直播商品
     */
    public LbsProduct selectById(Long id) {
      return lbsProductMapper.selectById(id);
    }

    /**
     * 查询直播商品列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 直播商品
     */
    public List<LbsProduct> selectList(LbsProductQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<LbsProduct> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        Long qrDeptZbjId = query.getDeptZbjId();
        if(qrDeptZbjId!=null) {
            qw.eq("dept_zbj_id", qrDeptZbjId);
        }
        Long pmsProductId = query.getPmsProductId();
        if (pmsProductId != null) {
            qw.eq("pms_product_id", pmsProductId);
        }
        Integer publishStatus = query.getPublishStatus();
        if (publishStatus != null) {
            qw.eq("publish_status", publishStatus);
        }
        Integer sort = query.getSort();
        if (sort != null) {
            qw.eq("sort", sort);
        }
        Long lbsZbjlId = query.getLbsZbjlId();
        if (lbsZbjlId != null) {
            qw.eq("lbs_zbjl_id", lbsZbjlId);
        }
        Integer sfqj = query.getSfqj();
        if (sfqj != null) {
            qw.eq("sfqj", sfqj);
        }
        return lbsProductMapper.selectList(qw);
    }


	 
    
	
	public void activityTopProduct(LbsProduct lbsProduct) {
		try {
			int sfqj = lbsProduct.getSfqj();
			LbsProduct lbsProductUptate = lbsProductMapper.selectById(lbsProduct.getId());
			int tpmSfqj = 2;
			if(sfqj == 1) {
				tpmSfqj = 1;
				UpdateWrapper<LbsProduct> updateWrapper = new UpdateWrapper<LbsProduct>();
	    		updateWrapper.set("sfqj", 0);
	    		updateWrapper.set("update_by", SecurityUtils.getUserId());
	    		updateWrapper.set("update_time", LocalDateTime.now());
	    		super.update(updateWrapper.eq("lbs_zbjl_id", lbsProduct.getLbsZbjlId()).eq("del_flag",0));
			}else {
				tpmSfqj = 2;
			}
			
			productVideoService.activityTopProduct(lbsProduct.getLbsZbjlId(), lbsProduct.getId(),tpmSfqj);
			lbsProductUptate.setSfqj(sfqj);
			lbsProductUptate.setUpdateBy(SecurityUtils.getUserId());
			lbsProductUptate.setUpdateTime(LocalDateTime.now());
    		lbsProductMapper.updateById(lbsProductUptate);
    		
		} catch (Exception e) {
			e.printStackTrace();
	        throw new RuntimeException("操作失败，请重试:"+e.getMessage());
		}
	}
	
    /**
     * 新增直播商品
     *
     * @param lbsProduct 直播商品
     * @return 结果
     */
    @Transactional
    public void insert(LbsAddProductQuery lbsAddProductQuery) {
    	
    	Long zbjid = lbsAddProductQuery.getZbjid() ;
    	
        Long deptZbjId = lbsZbjlMapper.selectById(zbjid).getDeptZbjId();;

    	String redirectImage = sysConfigService.selectConfigByKey("mall.lbs.pic");
        String redirectUrl = sysConfigService.selectConfigByKey("mall.lbs.link");
         
    	List<LbsProduct> lbsProducts = lbsAddProductQuery.getLbsProducts();
    	Long[] delIds = lbsAddProductQuery.getDelIds();
    	List<Long> delId2s = new ArrayList<Long>();
    	
    	if(lbsProducts!=null && lbsProducts.size()>0) {
    		Map<Long, Object> map = new HashMap<Long, Object>();
    		for (LbsProduct lbsProduct : lbsProducts) {
    			Long key = lbsProduct.getPmsProductId();
				if(map.containsKey(key)) {
			        throw new RuntimeException("商品id为："+ key + " 已经存在,不能重复添加！");
				}
				map.put(key, key);
			}
    	}
    	
    	List<ProductMsgAPI> productList = new ArrayList<ProductMsgAPI>();
    	List<LbsProduct> insertLbsProducts = new ArrayList<LbsProduct>();
    	
    	if(lbsProducts!=null) {
    		for (int i = 0; i < lbsProducts.size(); i++) {
        		LbsProduct lbsProduct = lbsProducts.get(i);
        		Long productId = lbsProduct.getPmsProductId();
        		Long id = lbsProduct.getId();
            	Product product =  productMapper.selectById(productId);
            	ProductMsgAPI productMsgAPI = new ProductMsgAPI();
            	productMsgAPI.setId(id);
            	productMsgAPI.setIndex(i);
            	productMsgAPI.setTitle(product.getName());
            	productMsgAPI.setIntroduceImage(product.getPic());
            	productMsgAPI.setHighlight("¥"+product.getPrice().toString());
            	productMsgAPI.setRedirectImage(redirectImage);
            	
            	if(redirectUrl!=null) {
                	productMsgAPI.setRedirectUrl(redirectUrl.replaceAll("P_ID", productId+""));
            	}
            	productMsgAPI.setEnableStatus(lbsProduct.getPublishStatus());
            	productList.add(productMsgAPI);
            	lbsProduct.setSort(i);
        		lbsProduct.setDelFlag(0);
        		
        		if(id != null) {
            		lbsProduct.setSfqj(lbsProduct.getSfqj());
            		//lbsProductMapper.deleteById(lbsProduct.getId());
            	}else {
            		lbsProduct.setSfqj(0);
            	}
        		
        		
        		lbsProduct.setCreateBy(SecurityUtils.getUserId());
        		lbsProduct.setCreateTime(LocalDateTime.now());
        		insertLbsProducts.add(lbsProduct);
    		}
    	}
        		
        		/** 这里先屏蔽用于暂时解决商品讲解问题
            	if(id != null) {
            		lbsProduct.setUpdateBy(SecurityUtils.getUserId());
            		lbsProduct.setUpdateTime(LocalDateTime.now());
            		lbsProductMapper.updateById(lbsProduct);
            		
            	}else {
            		lbsProduct.setSfqj(0);
            		lbsProduct.setCreateBy(SecurityUtils.getUserId());
            		lbsProduct.setCreateTime(LocalDateTime.now());
            		insertLbsProducts.add(lbsProduct);
            	}*/
        		
//            	if(id!=null) {
////            		lbsProduct.setUpdateBy(SecurityUtils.getUserId());
////            		lbsProduct.setUpdateTime(LocalDateTime.now());
////            		lbsProductMapper.updateById(lbsProduct);
//            		delId2s.add(id);
//            	}else {
//            		lbsProduct.setSfqj(0);
//            	}
//        		
//        		lbsProduct.setCreateBy(SecurityUtils.getUserId());
//        		lbsProduct.setCreateTime(LocalDateTime.now());
//        		insertLbsProducts.add(lbsProduct);
//            		
//    		}
//    	}
//    	if(delIds!=null && delIds.length>0) {
//    		deleteByIds(delIds);
//    	}
//    	if(delId2s!=null && delId2s.size()>0) {
//    		deleteByIds((Long[])delId2s.toArray());
//    	}
    	
    	UpdateWrapper<LbsProduct> updateWrapper= new UpdateWrapper<LbsProduct>();
    	updateWrapper.eq("lbs_zbjl_id", zbjid);
    	lbsProductMapper.delete(updateWrapper);
    	try {
    		 List<com.volcengine.model.livesaas.response.GetActivityProductAPIResponse.ProductMsgAPI>  retProduct = productVideoService.updateActivityProduct(zbjid, productList);
	    	 if(retProduct!=null) {
	    		 for (int i = 0; i < retProduct.size(); i++) {
	 	    		com.volcengine.model.livesaas.response.GetActivityProductAPIResponse.ProductMsgAPI productMsgAPI = retProduct.get(i);
	 				for (LbsProduct saveLbsProduct : insertLbsProducts) {
	 					if(productMsgAPI.getIndex().equals(saveLbsProduct.getSort())) {
	 						saveLbsProduct.setId(productMsgAPI.getId());
	 						saveLbsProduct.setDeptZbjId(deptZbjId);
	 						lbsProductMapper.insert(saveLbsProduct);
	 					}
	 				}
	 			}
	    	 }
    		
		} catch (Exception e) {
			e.printStackTrace();
	        throw new RuntimeException("操作失败，请重试:"+e.getMessage());
		}
    
       
    }

    /**
     * 修改直播商品
     *
     * @param lbsProduct 直播商品
     * @return 结果
     */
    public int update(LbsProduct lbsProduct) {
        return lbsProductMapper.updateById(lbsProduct);
    }

    /**
     * 批量删除直播商品
     *
     * @param ids 需要删除的直播商品主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        return lbsProductMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除直播商品信息
     *
     * @param id 直播商品主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return lbsProductMapper.updateDelFlagByIds(ids);
    }

}
